
import base64
import hashlib
import hmac
import urllib
from collections import Counter
from datetime import datetime, timedelta
import time
import pymysql
from dingtalkchatbot.chatbot import DingtalkChatbot


def reqtxt():
    # 获取今天的日期
    today = datetime.today()

    dates = []
    # 获取本周的起始日期（周一）和结束日期（周日）
    # start_of_week = today - timedelta(days=today.weekday())  # 本周一
    # start_of_week_str = start_of_week.strftime("%Y-%m-%d")
    # dates.append(start_of_week_str)
    # end_of_week = start_of_week + timedelta(days=4)  # 本周五
    # end_of_week_str = end_of_week.strftime("%Y-%m-%d")

    # 计算上周的周一日期
    last_monday = today - timedelta(days=today.weekday()) - timedelta(weeks=1)

    # 输出上周周一到周五的日期
    for i in range(5):
        date = last_monday + timedelta(days=i)
        # print(date.strftime("%Y-%m-%d"))
        dates.append((date.strftime("%Y-%m-%d")))

    # for i in range(1, 5):
    #     dates.append((start_of_week + timedelta(days=i)).strftime("%Y-%m-%d"))

    config = {
        'host': '192.168.3.10',
        'user': 'testuser',
        'password': 'test1234',
        'database': 'pro_schedule',
        'charset': 'utf8mb4',
    }

    conn = pymysql.connect(**config)
    cursor = conn.cursor()
    names = []
    for date in dates:
        cursor.execute(
            "SELECT realname FROM pro_userinfo AS a LEFT JOIN pro_dailywork  AS b ON a.useridx = b.useridx AND b.updatetime LIKE '%{}%' LEFT JOIN pro_idle_people AS c ON a.useridx = c.useridx AND c.addtime LIKE '%{}%'WHERE b.useridx IS NULL AND a.dimission = 0 AND c.useridx IS NULL AND a.postid>0 AND a.realname <> '夏玲珠PM';".format(
                date, date))

        rows = cursor.fetchall()  # 获取所有结果
        for row in rows:
            # print(row[0])
            names.append(row[0])
        # conn.commit()
    # print(names)

    element_counts = Counter(names)
    #print('以下是上周未写日报的人员名单：')
    result = []
    for element, count in element_counts.items():
        #print(f"{element}: {count} 次")
        result.append(f"{element}: {count} 次")
    #print( ",".join(result))
    txt = ','.join(result)
    return txt

def getDingtalkRemind(txt):
    timestamp = str(round(time.time() * 1000))

    robot_webhook = "https://oapi.dingtalk.com/robot/send?access_token=781ba6ff8c616278b61c5250e622dfcb645874a7abfd85fc5d6f61136e5df491"
    secret = "SECaf15bbd8742641183d1b8c790125f6ddb915a05ddcb98e4061218e3055249cde"
    #robot_webhook = "https://oapi.dingtalk.com/robot/send?access_token=5ee32a1beed3c7810e7a2d7d94db55ad48144ce25456716171a7aebf82d6883f"
    #secret = "SECb5273c8838985e8638c5681a3a170fa79ff2178ade24065142d32989819ad28f"

    secret_enc = secret.encode("utf-8")
    string_to_sign = "{}\n{}".format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode("utf-8")
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

    webhook = f"{robot_webhook}&timestamp={timestamp}&sign={sign}"

    msg_text = "以下是上周未写日报的人员名单：\n" + txt

    msgs = DingtalkChatbot(webhook)

    '''
    at_mobiles: 被@的人的手机号 eg: ['138xxxxxxxx', '136xxxxxxxx']
    is_at_all : 是否 @ 全员
    '''
    states = msgs.send_text(msg=(msg_text), at_mobiles=[], is_at_all=True)

    #写入日志
    with open('dailyReport.txt','a', encoding="utf-8") as file:
        # 获取当前日期和时间
        now = datetime.now()
        file.write(now.strftime("%Y-%m-%d %H:%M:%S")+'\n')
        file.write(msg_text+'\n')
        file.write(f"钉钉机器人消息状态: {states}"+'\n')


if __name__ == '__main__':
    content = reqtxt()
    if content:
        getDingtalkRemind(content)
    else:
        print("本周大家都严格执行了日报，太棒了！")

